package top.hkyzf.study.leetcode.linkedlist;

import org.junit.Test;

/**
 * @author 朱峰
 * @date 2022-1-23 18:09
 */
public class 删除链表的倒数第N个结点_19 {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode node = new ListNode(-1, head);
        ListNode prev = node;
        ListNode next = node;
        int index = 0;
        while (next != null) {
            if (index > n) {
                prev = prev.next;
            }
            next = next.next;
            index++;
        }
        prev.next = prev.next.next;
        return node.next;
    }

    @Test
    public void testRemoveNthFromEnd () {
        ListNode node6 = new ListNode(6);
        ListNode node5 = new ListNode(5, node6);
        ListNode node4 = new ListNode(4, node5);
        ListNode node3 = new ListNode(3, node4);
        ListNode node2 = new ListNode(2, node3);
        ListNode head = new ListNode(1, node2);
        ListNode node = removeNthFromEnd(head, 6);
        while (node != null) {
            System.out.println(node.val);
            node = node.next;
        }
    }
}
